package com.markerhub.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.User;
import com.markerhub.service.UserService;
import com.markerhub.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    //@RequiresRoles("root")
    @PostMapping("/reset-password/{id}")
    public Result resetPassword(@PathVariable Long id) {
        log.info("Resetting password for user ID: {}", id);

        try {
            User user = userService.getById(id);
            if (user == null) {
                return Result.fail("用户不存在");
            }

            user.setPassword(SecureUtil.md5("123456"));
            userService.updateById(user);

            return Result.succ("密码重置成功");
        } catch (Exception e) {
            log.error("Reset password failed for user ID: " + id, e);
            return Result.fail("密码重置失败：" + e.getMessage());
        }
    }
    @RequiresAuthentication
    @GetMapping("/index")
    public Result index() {
        User user = userService.getById(1L);
        return Result.succ(user);
    }


   // @RequiresRoles("root")
    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {
        Page page = new Page(currentPage, 10);
        IPage pageData = userService.page(page, new QueryWrapper<User>());
        return Result.succ(pageData);
    }

    //@RequiresRoles("root")
    @GetMapping("/search")
    public Result list(String username,
                       @RequestParam(defaultValue = "1") Integer currentPage,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Page<User> page = new Page<>(currentPage, pageSize);
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            // 添加用户名模糊搜索条件
            if (StrUtil.isNotBlank(username)) {
                wrapper.like(User::getUsername, username);
            }
            // 按创建时间降序排序
            wrapper.orderByDesc(User::getCreated);
            IPage<User> userPage = userService.page(page, wrapper);
            return Result.succ(userPage);
        } catch (Exception e) {
            log.error("获取用户列表失败:", e);
            return Result.fail("获取用户列表失败");
        }
    }

   // @RequiresRoles("root")
    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        // 新增用户时，设置默认密码和创建时间
        if (user.getId() == null) {
            user.setPassword(SecureUtil.md5("123456"));
            user.setCreated(LocalDateTime.now());
            user.setStatus(1); // 设置默认状态为启用
        } else {
            // 更新用户时，不更新密码
            User existUser = userService.getById(user.getId());
            Assert.notNull(existUser, "用户不存在");
            user.setPassword(existUser.getPassword());
        }

        userService.saveOrUpdate(user);
        return Result.succ("操作成功");

    }
    //@RequiresRoles("root")
    @PostMapping("/status/change")
    public Result changeStatus(@RequestBody User user) {
        User existUser = userService.getById(user.getId());
        Assert.notNull(existUser, "用户不存在");
        existUser.setStatus(user.getStatus());
        userService.updateById(existUser);
        return Result.succ("状态更新成功");
    }
   // @RequiresRoles("root")
    @GetMapping("/info/{id}")
    public Result info(@PathVariable Long id) {
        User user = userService.getById(id);
        Assert.notNull(user, "用户不存在");
        return Result.succ(user);
    }
}
